<template lang="html">
  <d2-container class="organ-wrapper">
    <el-row>
      <el-col :span="10">
        <el-card shadow="never" class="mr10 table-page-full">
          <div slot="header" class="card-header fbc">
            <span>部门列表</span>
            <el-button v-has="'organAdd'" type="text" @click="doAdd()">新增</el-button>
          </div>

          <div v-loading="leftTreeLoading" class="tree-wrapper">
            <el-tree
              ref="orgTree"
              lazy
              node-key="id"
              :highlight-current="true"
              :props="{
                children: 'childList',
                label: 'shortName',
                isLeaf: 'leaf',
              }"
              :load="loadOrgNode"
              @node-click="handleNodeClick"
            >
              <span slot-scope="{ node, data }" class="custom-tree-node pr10 fbc">
                <span>{{ node.label }}</span>
                <span class="active">
                  <el-button
                    v-has="'organChildAdd'"
                    type="text"
                    class="ml10"
                    @click.stop="doAdd({ node, data })"
                    >新增
                  </el-button>
                  <el-button
                    v-has="'organDel'"
                    type="text"
                    class="ml10"
                    @click.stop="doDel({ node, data })"
                    >删除
                  </el-button>
                </span>
              </span>
            </el-tree>
          </div>
        </el-card>
      </el-col>

      <el-col :span="14">
        <el-card shadow="never" class="table-page-full">
          <div slot="header" class="card-header fbc">
            <span>{{ isEdit ? "编辑" : "新增" }}部门</span>
            <el-button
              v-if="isEdit"
              v-has="'organEdit'"
              type="text"
              :loading="btnLoading"
              @click="doSubmit"
              >提交
            </el-button>
            <el-button v-else type="text" :loading="btnLoading" @click="doSubmit">确定</el-button>
          </div>

          <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="auto" class="mt10">
            <el-form-item label="上级部门" prop="parentName">
              <el-input v-model="ruleForm.parentName" disabled />
            </el-form-item>

            <el-form-item label="部门全称" prop="fullName">
              <el-input v-model="ruleForm.fullName" placeholder="请输入" />
            </el-form-item>

            <el-form-item label="部门简称" prop="shortName">
              <el-input v-model="ruleForm.shortName" placeholder="请输入" />
            </el-form-item>

            <el-form-item v-if="hotelShowFlag" label="部门编码" prop="uniqueCode">
              <el-input
                v-model="ruleForm.uniqueCode"
                placeholder="请输入"
              />
            </el-form-item>

            <el-form-item label="所属地区" prop="areaId">
              <tree-select
                ref="areaTree"
                :lazy="true"
                placeholder="请选择"
                :props="{
                  value: 'areaId',
                  label: 'name',
                  children: 'childList',
                  isLeaf: 'leaf',
                }"
                :searchApi="AreaSearch"
                :loadTreeApi="AreaTree"
                searchParamsKey="areaName"
                :options.sync="areaTreeData"
                :value="ruleForm.areaId"
                @getValue="getAreaValue"
              />
            </el-form-item>

            <el-form-item label="部门类型" prop="orgType">
              <el-select v-model="ruleForm.orgType" placeholder="请选择">
                <el-option
                  v-for="(item, index) in orgTypeOptions"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="行政等级" prop="level">
              <el-select v-model="ruleForm.level" placeholder="请选择">
                <el-option
                  v-for="(item, index) in orgLevelOptions"
                  :key="index"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="排序" prop="sortBy">
              <el-input-number v-model="ruleForm.sortBy" :min="1" />
            </el-form-item>

            <el-form-item label="描述" prop="remarks">
              <el-input v-model="ruleForm.remarks" type="textarea" rows="4" placeholder="请输入" />
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </d2-container>
</template>

<script>
import { AreaTree, AreaSearch } from "api/sys/area";
import {
  OrganizeTree,
  OrganizeUpdate,
  OrganizeAdd,
  OrganizeDel,
} from "api/sys/organize";
import { DictKeys } from "api/sys/dict";
import rules from "./config/rules";
import TreeSelect from "components/tree-select";
import { DdOrg } from "api/dd";

export default {
  components: {
    TreeSelect,
  },
  data() {
    return {
      hotelShowFlag: true,
      ruleForm: {
        // 上级部门名称
        parentName: "",
        // 上级部门id
        parentId: 0,
        // 部门编码
        uniqueCode: "",
        // 部门id
        id: "",
        // 部门全称
        fullName: "",
        // 部门简称
        shortName: "",
        // 地区名称
        areaName: "",
        // 地区id
        areaId: "",
        // 组织类型
        orgType: "1",
        // 行政等级
        level: "",
        // 排序
        sortBy: "",
        // 描述
        remarks: "",
      },
      // 校验规则
      rules,
      // 左侧容器的加载
      leftTreeLoading: false,
      // 是否为编辑
      isEdit: false,
      // 地区树形数据
      areaTreeData: [],
      // 行政等级配置文件
      orgLevelOptions: [],
      // 组织类型配置文件
      orgTypeOptions: [],
      // 设备列表
      boxOptions: [],
      // 部门编码列表
      hotelCodeOptions: [],
      // 提交按钮的加载动画
      btnLoading: false,
    };
  },
  created() {
    this._DictKeys();
  },
  methods: {
    AreaSearch,
    AreaTree,
    /**
     * 获取地区数据
     */
    async _AreaTree({ parentId = 0 } = {}) {
      try {
        const data = await AreaTree(parentId);
        return data;
      } catch (e) {
        console.log(e);
      }
    },
    /**
     * 加载地区数据
     */
    async loadAreaNode({ node, resolve }) {
      const {
        data: { areaId },
      } = node;
      const data = await this._AreaTree({ parentId: areaId });
      return resolve(this.treeDataFormat(data));
    },
    /**
     * 左侧新增
     */
    async doAdd({ data, node } = {}) {
      this.isEdit = false;
      const baseFrom = {
        shortName: "",
        areaId: "",
        areaName: "",
        orgType: "1",
        level: "",
        remarks: "",
        fullName: "",
      };
      if (data) {
        const { shortName, subCount, id } = data;
        Object.assign(this.ruleForm, {
          parentName: shortName,
          parentId: id,
          sortBy: subCount + 1,
          ...baseFrom,
        });
        this.currentNode = node;
      } else {
        // 添加最上级数据
        const sortBy = this.$refs.orgTree.root.childNodes.length + 1;
        Object.assign(this.ruleForm, {
          parentName: "",
          parentId: "",
          id: 0,
          sortBy,
          ...baseFrom,
        });
        this.currentNode = null;
      }
      await this.$nextTick();
      this.$refs.ruleForm.clearValidate();
    },
    /**
     * 部门删除
     */
    async doDel({ node, data }) {
      const { id } = data;
      await this.$myConfirm("删除该部门");
      try {
        await OrganizeDel(id);
        this.$message.success("部门删除成功");
        node.parent.loaded = false;
        node.parent.expand();
        this.formReset();
      } catch (e) {
        console.log(e);
      }
    },
    /**
     * 树节点的点击事件
     */
    handleNodeClick(data, node) {
      this.$refs.ruleForm.resetFields();
      this.hotelShowFlag = true;
      if (node.parent.data) {
        this.ruleForm.parentName = node.parent.data.shortName;
      } else {
        this.ruleForm.parentName = "无";
        if (data.orgType === "2") {
          this.hotelShowFlag = false;
        }
      }
      this.$refs.ruleForm.clearValidate();
      this.isEdit = true;
      Object.assign(this.ruleForm, data);

      this.$refs.areaTree.setTempTitle(data.areaName);
      // 设置当前选中的节点对象
      this.currentNode = node;
    },
    /**
     * 获取左侧树形结构的数据
     */
    async _OrganizeTree({ parentId = 0 } = {}) {
      try {
        const data = await OrganizeTree(parentId);
        return data || [];
      } catch (e) {
        console.log(e);
      }
    },
    /**
     * 提交
     */
    doSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.btnLoading = true;
          this.isEdit ? this._OrganizeUpdate() : this._OrganizeAdd();
        } else {
          return false;
        }
      });
    },
    /**
     * 表单的重置
     */
    formReset() {
      this.$refs.ruleForm.resetFields();
      this.isEdit = false;
    },
    /**
     * 新增
     */
    async _OrganizeAdd() {
      const { leaf, subCount, id, parentId,  ...obj } = this.ruleForm;
      try {
        obj.parentId = Number(parentId);
        await OrganizeAdd(obj);
        this.$message.success("部门新增成功");
        this.formReset();
        // 刷新数据
        if (this.currentNode) {
          this.currentNode.loaded = false;
          this.currentNode.expand();
        } else {
          this.$refs.orgTree.root.loaded = false;
          this.$refs.orgTree.root.expand();
        }
      } catch (e) {
        console.log(e);
      } finally {
        this.btnLoading = false;
      }
    },
    /**
     * 编辑
     */
    async _OrganizeUpdate() {
      const { leaf, subCount, parentName,  ...obj } = this.ruleForm;
      try {
        await OrganizeUpdate(obj);
        this.$message.success("区域编辑成功");
        this.$refs.ruleForm.resetFields();
        // 刷新数据
        this.currentNode.parent.loaded = false;
        this.currentNode.parent.expand();
        this.formReset();
      } catch (e) {
        console.log(e);
      } finally {
        this.btnLoading = false;
      }
    },
    /**
     * 加载部门数据
     */
    async loadOrgNode(node, resolve) {
      // 第一次加载数据
      if (node.level === 0) {
        this.leftTreeLoading = true;
        let data = await this._OrganizeTree();
        const { length } = data;
        if (length) {
          data = this.treeDataFormat(data);
        }
        this.leftTreeLoading = false;
        return resolve(data);
      } else {
        const {
          data: { id },
        } = node;
        const data = await this._OrganizeTree({ parentId: id });
        return resolve(this.treeDataFormat(data));
      }
    },

    /**
     * 树形数据格式化
     */
    treeDataFormat(arr) {
      arr.map((item) => {
        const { subCount, areaId } = item;
        item.leaf = !subCount;
        if (areaId) {
          item.areaId = areaId.toString();
        }
      });
      return arr.sort((a, b) => a.sortBy - b.sortBy);
    },
    /**
     * 获取部门数据
     */
    getAreaValue(val) {
      if (val) {
        const { areaId, name: areaName } = val;
        Object.assign(this.ruleForm, { areaId, areaName });
      } else {
        Object.assign(this.ruleForm, { areaId: "", areaName: "" });
      }
    },
    async downDdOrg() {
      await this.$myConfirm("确定同步钉钉组织信息");
      this.leftTreeLoading = true;
      try {
        await DdOrg();
        this.$message.success("同步钉钉组织信息");
      } catch (e) {
        console.log(e);
      }
      this.leftTreeLoading = false;
    },
    /**
     * 获取数据字典
     */
    async _DictKeys() {
      try {
        const tempArr = ["org_type", "org_level"];
        const data = await DictKeys(tempArr.join());
        if (data) {
          const { org_level: orgLevel, org_type: orgType } = data;
          this.orgLevelOptions = orgLevel;
          this.orgTypeOptions = orgType;
        }
      } catch (e) {
        console.log(e);
      }
    },
    
  },
};
</script>

<style lang="scss" scoped>
.organ-wrapper {
  .custom-tree-node {
    flex: 1;

    &:hover {
      .active {
        display: block;
      }
    }
  }

  .table-page-full {
    height: calc(100vh - 118px);
    overflow: auto;
    overflow-x: hidden;

    .tree-wrapper {
      height: calc(100vh - 180px);
    }
  }

  .active {
    display: none;
  }

  .card-header {
    ::v-deep .el-button {
      padding: 0 !important;
    }
  }
}
</style>
